package demo.mina;


import demo.mina.util.BitOperator;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.textline.TextLineEncoder;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;

/**
 *
 */
public class MinaClient {

    public static void main(String[] args) {
        NioSocketConnector nioSocketConnector = new NioSocketConnector();
        // 添加过滤链
        nioSocketConnector.getFilterChain().addLast("logger", new LoggingFilter());
        // 设置协议解析过滤器
        nioSocketConnector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MysqlProtocolFactory()));
        nioSocketConnector.setHandler(new MinaClientHandler());
        // 设置缓冲区大小和空闲属性
        nioSocketConnector.getSessionConfig().setReadBufferSize(2048);
        nioSocketConnector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

        ConnectFuture connectFuture = nioSocketConnector.connect(new InetSocketAddress(3306));
    }

    public static class MysqlProtocolFactory implements ProtocolCodecFactory {

        @Override
        public ProtocolEncoder getEncoder(IoSession ioSession) throws Exception {
            return new TextLineEncoder();
        }

        @Override
        public ProtocolDecoder getDecoder(IoSession ioSession) throws Exception {
            return new MysqlProtocolDecoder();
        }
    }


    public static class MysqlProtocolDecoder extends CumulativeProtocolDecoder {

        @Override
        protected boolean doDecode(IoSession ioSession, IoBuffer ioBuffer, ProtocolDecoderOutput protocolDecoderOutput) throws Exception {
            byte[] bytes = new byte[ioBuffer.remaining()];
            ioBuffer.get(bytes);
            protocolDecoderOutput.write(bytes);
            return true;
        }
    }


    public static class MinaClientHandler extends IoHandlerAdapter {

        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            byte[] bytes = (byte[]) message;
            IoBuffer ioBuffer = IoBuffer.wrap(bytes);
            byte[] len = new byte[3];
            ioBuffer.get(len);
            System.out.printf("包长度：%d%n", BitOperator.byteToInteger(len));
            System.out.printf("包数量：%d%n", ioBuffer.get());
            System.out.printf("协议版本号：%b%n", ioBuffer.get());
        }
    }

}
